package cn.liyicun.test.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ImageUtil;
import cn.hutool.core.util.RandomUtil;
import cn.liyicun.test.service.UserFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Random;
import java.util.RandomAccess;

@Controller
@Slf4j
public class UploadController extends BaseController {


    @Value("${upload.filePath}")
    String filePath;
    @Value("${upload.domain}")
    String domain;
    @Autowired
    UserFileService service;

    @GetMapping("/upload")
    public String upload(HttpServletRequest req, HttpServletResponse res) throws IOException {


        Long uid = isLogin(req, res, true);
        if (uid <= 0) {
            return null;
        }


        return "upload";
    }

    String[] type1 = {"jpg", "png", "gif","jpeg"};
    String[] type2 = {"rmvb", "flv", "mp3", "mp4", "mpg", "wav", "avi"};

    @PostMapping("/upload")
    public ModelAndView upload(HttpServletRequest req, HttpServletResponse res,
                               @RequestParam(name = "protocol", required = true) String protocol,
                               @RequestParam(name = "radio_level", required = true) String radio_level,
                               @RequestParam(name = "captcha", required = true) String captcha,
                               @RequestParam("file") MultipartFile[] files, ModelAndView model) throws IOException {
        model.setViewName("uploadSuccess");
        if (!"1".equals(protocol)) {
            model.addObject("error", "必须同意网址协议！");
            return model;
        }
        Long uid = isLogin(req, res, true);
        if (uid <= 0) {
            return null;
        }
        if (uid.longValue()==10) {
            model.addObject("error", "默认账号不能分享信息");
            return model;
        }
        if (!_captcha(req, captcha)) {
            model.addObject("error", "验证码错误！");
            return model;
        }

        log.info(files.length + "----------");

        if (files.length == 0) {
            model.addObject("error", "上传失败，请选择文件");
            return model;
        }
        String mfileName = "";
        long id = 0;
        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();
            String ext = FileUtil.extName(fileName);

            log.info("fileName,:{},ext:{},ext:{}", fileName, ext, ext);

            int catid = 0;
            if (Arrays.asList(type1).contains(ext)) {
                catid = 1;


                //ImageUtil.scale()
            }
            if (Arrays.asList(type2).contains(ext)) {
                catid = 2;
            }
            if (catid == 0) {
                model.addObject("error", "该文件不能上传" + fileName);
                return model;

            }
            DateTime date = new DateTime();
            String fileNameTemp = "/file/";
            fileNameTemp +=  date.toString("yyyy/MMdd/HHmmssSSS") + "_";
            fileNameTemp += RandomUtil.randomString(10) + "." + ext;
            File dest = new File(filePath + fileNameTemp);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
                dest.setReadable(true, false);
            } catch (IOException e) {
                e.printStackTrace();
                model.addObject("error", e.getMessage());
                return model;
            }
            id = service.addFile(uid, fileNameTemp, fileNameTemp, catid, Integer.valueOf(radio_level), 1, 0, ext);
            mfileName = fileNameTemp;
        }


        model.addObject("link", domain + mfileName);
        model.addObject("id", id);
        model.addObject("url", mfileName);
        return model;
    }

}